package com.code.generate.util;


import com.code.generate.model.JdbcConfig;
import com.code.generate.model.Project;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.druid.DruidPlugin;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GCM_DB_util {

    public synchronized static DbPro getDb(Project project) throws Exception {

        if (project.getJdbcConfigId() == null) {
            throw new Exception("项目没有配置数据源");
        }
        JdbcConfig jdbcConfig = JdbcConfig.dao.findById(project.getJdbcConfigId());
        try {
            DbPro dbPro = Db.use(jdbcConfig.getJdbcConfigId().toString());
            if (dbPro != null) {
                return dbPro;
            }
        } catch (Exception e) {

        }
        log.info(jdbcConfig.getJdbcConfigId().toString() + "  没有数据源 开始创建");
        log.info(" druidPlugin  url : {},  username : {},  password : {}",jdbcConfig.getJdbcUrl(),jdbcConfig.getUser(),jdbcConfig.getPassword());
        DruidPlugin druidPlugin = new DruidPlugin(jdbcConfig.getJdbcUrl(), jdbcConfig.getUser(),
                jdbcConfig.getPassword());
        log.info(" druidPlugin.start() - begin");
        druidPlugin.start();
        log.info(" druidPlugin.start() - end");
        // me.add(druidPlugin);
        // 配置ActiveRecord插件
        log.info(" plugin.start() - begin");
        ActiveRecordPlugin plugin = new ActiveRecordPlugin(jdbcConfig.getJdbcConfigId().toString(), druidPlugin);
        plugin.start();
        log.info(" plugin.start() - end");
        return Db.use(jdbcConfig.getJdbcConfigId().toString());
    }
}
